<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生管理 - 教务管理系统</title>
    <link rel="stylesheet" href="css/common.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; color: #333; background: #f8f9fa; }
        header { background-color: #007BFF; color: white; padding: 0 40px; height: 60px; display: flex; align-items: center; }
        .logo { font-size: 1.3em; font-weight: bold; margin-right: 40px; }
        nav { display: flex; align-items: center; width: 100%; }
        .nav-left { flex: 1; display: flex; align-items: center; }
        .nav-center { flex: 2; display: flex; justify-content: center; }
        .nav-center a { color: white; text-decoration: none; margin: 0 18px; font-size: 1.1em; transition: text-decoration 0.2s; }
        .nav-center a.active, .nav-center a:hover { text-decoration: underline; }
        .nav-right { flex: 1; text-align: right; font-size: 1em; }
        main { padding: 40px 20px 20px 20px; }
        .title { font-size: 2em; color: #007BFF; margin-bottom: 18px; }
        .desc { margin-bottom: 24px; color: #555; }
        .actions { margin-bottom: 18px; display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
        .modal-bg {
            display: none; position: fixed; left: 0; top: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.2); z-index: 1000;
        }
        .modal {
            background: #fff; border-radius: 8px; box-shadow: 0 2px 12px #e0e0e0; width: 350px; max-width: 90vw; padding: 28px 24px 18px 24px; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);
        }
        .modal-title { font-size: 1.2em; color: #007BFF; margin-bottom: 18px; text-align: center; }
        .modal label { display: block; margin-bottom: 6px; color: #555; }
        .modal input, .modal select { width: 100%; padding: 7px 10px; margin-bottom: 14px; border: 1px solid #ccc; border-radius: 4px; }
        .modal-btns { text-align: right; }
        .modal-btns button { margin-left: 10px; padding: 7px 18px; border-radius: 4px; border: none; cursor: pointer; }
        .modal-btns .ok { background: var(--success-color); color: #fff; }
        .modal-btns .ok:hover { background: var(--success-dark); }
        .modal-btns .cancel { background: var(--danger-color); color: #fff; }
        .modal-btns .cancel:hover { background: var(--danger-dark); }
        @media (max-width: 900px) {
            main { padding: 20px 5px; }
            .title { font-size: 1.3em; }
        }
    </style>
</head>
<body>
    <header>
        <nav style="width:100%;display:flex;align-items:center;">
            <div class="nav-left"><span class="logo">教务管理系统</span></div>
            <div class="nav-center" id="navLinks">
                <a href="index.html">首页</a>
                <a href="student.html" class="active admin-teacher-link">学生管理</a>
                <a href="attendance.html" class="admin-teacher-link">考勤管理</a>
                <a href="user.html" class="admin-only-link">用户管理</a>
            </div>
            <div class="nav-right">
                <span id="userName" style="cursor:pointer;position:relative;">admin
                    <span id="logoutMenu" style="display:none;position:absolute;right:0;top:28px;background:#fff;border:1px solid #ccc;border-radius:4px;box-shadow:0 2px 8px #e0e0e0;padding:0 0;z-index:10;min-width:120px;">
                        <a href="userinfo.html" style="color:#007BFF;text-decoration:none;display:block;padding:8px 18px;text-align:center;" onclick="closeMenu()">个人信息</a>
                        <a href="login.html" style="color:#007BFF;text-decoration:none;display:block;padding:8px 18px;text-align:center;border-top:1px solid #eee;" onclick="logout()">退出登录</a>
                    </span>
                </span>
            </div>
        </nav>
    </header>
    <main>
        <div class="title">学生信息管理</div>
        <div class="desc">可对学生的学号、姓名、班级等基本信息进行增删改查操作。</div>
        <div class="actions">
            <button class="btn btn-primary admin-only-btn" onclick="showAddStudent()">新增学生</button>
            <button class="btn btn-info admin-only-btn" onclick="showManageClass()">班级管理</button>
            <button class="btn btn-warning" onclick="exportStudents()">导出</button>
            <div style="margin-left: auto; display: flex; align-items: center; gap: 10px;">
                <select id="classSelect" onchange="searchStudents()">
                    <option value="">全部班级</option>
                </select>
                <input id="searchInput" type="text" placeholder="搜索学生姓名/学号" style="padding:8px 12px; border-radius:4px; border:1px solid #ccc; width:180px;" />
                <button class="btn btn-success" onclick="searchStudents()">搜索</button>
            </div>
        </div>
        <div id="loadingIndicator" style="text-align:center; padding:20px; display:block;">
            <p>正在加载数据，请稍候...</p>
        </div>
        <table id="studentTable" style="display:none;">
            <thead>
                <tr>
                    <th>学号</th>
                    <th>姓名</th>
                    <th>班级</th>
                    <th>性别</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- 数据将在这里动态加载 -->
            </tbody>
        </table>
        <div class="modal-bg" id="addStudentBg">
            <div class="modal">
                <div class="modal-title">新增学生</div>
                <label>学号</label><input id="stuNoInput" type="text" placeholder="请输入学号" />
                <label>姓名</label><input id="stuNameInput" type="text" placeholder="请输入姓名" />
                <label>班级</label>
                <select id="stuClassInput">
                    <option value="软件工程1班">软件工程1班</option>
                    <option value="软件工程2班">软件工程2班</option>
                    <option value="计算机1班">计算机1班</option>
                </select>
                <label>性别</label>
                <select id="stuGenderInput">
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
                <div class="modal-btns">
                    <button class="ok" onclick="addStudent()">确定</button>
                    <button class="cancel" onclick="closeAddStudent()">取消</button>
                </div>
            </div>
        </div>
        <div class="modal-bg" id="addClassBg">
            <div class="modal">
                <div class="modal-title">新增班级</div>
                <label>班级名称</label><input id="classNameInput" type="text" placeholder="请输入班级名称" />
                <div class="modal-btns">
                    <button class="ok" onclick="addClass()">确定</button>
                    <button class="cancel" onclick="closeAddClass()">取消</button>
                </div>
            </div>
        </div>

        <div class="modal-bg" id="manageClassBg">
            <div class="modal" style="width: 500px;">
                <div class="modal-title">班级管理</div>
                <div style="max-height: 300px; overflow-y: auto;">
                    <table id="classTable" style="width: 100%; margin-bottom: 20px;">
                        <thead>
                            <tr>
                                <th>班级名称</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 班级列表将在这里动态生成 -->
                        </tbody>
                    </table>
                </div>
                <div class="modal-btns">
                    <button class="ok" onclick="showAddClass()">新增班级</button>
                    <button class="cancel" onclick="closeManageClass()">关闭</button>
                </div>
            </div>
        </div>
    </main>
    <script>
        // 检查用户是否已登录
        function checkLogin() {
            var user = localStorage.getItem('loginUser');
            if (!user) {
                // 未登录，重定向到登录页面
                window.location.href = 'login.html';
                return false;
            }
            return user;
        }

        // 根据用户角色控制页面显示
        function setupUIByRole() {
            var role = localStorage.getItem('userRole') || '';
            var userName = localStorage.getItem('userName') || localStorage.getItem('loginUser');

            // 设置用户名显示
            document.getElementById('userName').firstChild.textContent = userName;

            // 控制导航栏显示
            var adminTeacherLinks = document.querySelectorAll('.admin-teacher-link');
            var adminOnlyLinks = document.querySelectorAll('.admin-only-link');
            var adminOnlyBtns = document.querySelectorAll('.admin-only-btn');

            if (role === 'admin') {
                // 管理员可以看到
                adminTeacherLinks.forEach(link => link.style.display = 'inline');
                adminOnlyLinks.forEach(link => link.style.display = 'inline');
                adminOnlyBtns.forEach(btn => btn.style.display = 'inline-block');
            } else if (role === 'teacher') {
                // 老师可以看到学生管理和考勤管理，但不能增删学生和班级
                adminTeacherLinks.forEach(link => link.style.display = 'inline');
                adminOnlyLinks.forEach(link => link.style.display = 'none');
                adminOnlyBtns.forEach(btn => btn.style.display = 'none');
            } else if (role === 'student') {
                // 学生只能查看学生
                adminTeacherLinks.forEach(link => link.style.display = 'none');
                adminOnlyLinks.forEach(link => link.style.display = 'none');
                adminOnlyBtns.forEach(btn => btn.style.display = 'none');
            }
        }

        // 页面加载时获取班级列表和学生列表
        document.addEventListener('DOMContentLoaded', function() {
            // 验证登录状态
            var user = checkLogin();
            if (!user) return; // 如果未登录，已重定向到登录页面

            // 根据用户角色设置UI
            setupUIByRole();

            // 获取班级列表
            fetchClassList();

            // 获取学生列表
            fetchStudentList();
        });

        // 获取班级列表
        function fetchClassList() {
            fetch('/api/class/list')
                .then(response => response.json())
                .then(data => {
                    // 清空班级下拉框
                    var classSelect = document.getElementById('classSelect');
                    var stuClassInput = document.getElementById('stuClassInput');

                    // 保留"全部班级"选项
                    classSelect.innerHTML = '<option value="">全部班级</option>';
                    stuClassInput.innerHTML = '';

                    // 添加班级选项
                    data.forEach(cls => {
                        var option1 = document.createElement('option');
                        option1.value = cls.id;
                        option1.text = cls.name;
                        classSelect.appendChild(option1);

                        var option2 = document.createElement('option');
                        option2.value = cls.id;
                        option2.text = cls.name;
                        stuClassInput.appendChild(option2);
                    });
                })
                .catch(error => {
                    console.error('获取班级列表失败:', error);
                });
        }

        // 获取学生列表
        function fetchStudentList() {
            // 显示加载指示器，隐藏表格
            document.getElementById('loadingIndicator').style.display = 'block';
            document.getElementById('studentTable').style.display = 'none';

            var classId = document.getElementById('classSelect').value;
            var keyword = document.getElementById('searchInput').value.trim();

            var url = '/api/student/list';
            if (classId || keyword) {
                url += '?';
                if (classId) url += 'classId=' + classId;
                if (classId && keyword) url += '&';
                if (keyword) url += 'keyword=' + encodeURIComponent(keyword);
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    var tbody = document.querySelector('#studentTable tbody');
                    tbody.innerHTML = '';

                    if (data.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;">暂无数据</td></tr>';
                    } else {
                        // 按学号排序
                        data.sort((a, b) => a.studentId.localeCompare(b.studentId));

                        data.forEach(student => {
                            var tr = document.createElement('tr');
                            tr.innerHTML = `
                                <td>${student.studentId}</td>
                                <td>${student.name}</td>
                                <td>${student.className || ''}</td>
                                <td>${student.gender || ''}</td>
                                <td>
                                    <div class="action-buttons">
                                        <button class="btn btn-info admin-only-btn" onclick="editStudent(${student.id})">编辑</button>
                                        <button class="btn btn-danger admin-only-btn" onclick="deleteStudent(${student.id}, '${student.studentId}')">删除</button>
                                    </div>
                                </td>
                            `;
                            tbody.appendChild(tr);
                        });
                    }

                    // 隐藏加载指示器，显示表格
                    document.getElementById('loadingIndicator').style.display = 'none';
                    document.getElementById('studentTable').style.display = 'table';

                    // 重新应用角色权限控制
                    var adminOnlyBtns = document.querySelectorAll('.admin-only-btn');
                    var role = localStorage.getItem('userRole') || '';
                    if (role !== 'admin') {
                        adminOnlyBtns.forEach(btn => btn.style.display = 'none');
                    }
                })
                .catch(error => {
                    console.error('获取学生列表失败:', error);
                    var tbody = document.querySelector('#studentTable tbody');
                    tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;">获取学生数据失败: ' + error.message + '</td></tr>';

                    // 隐藏加载指示器，显示表格（即使有错误）
                    document.getElementById('loadingIndicator').style.display = 'none';
                    document.getElementById('studentTable').style.display = 'table';
                });
        }

        // 搜索学生
        function searchStudents() {
            fetchStudentList();
        }

        // 添加学生
        function addStudent() {
            var studentId = document.getElementById('stuNoInput').value.trim();
            var name = document.getElementById('stuNameInput').value.trim();
            var classId = document.getElementById('stuClassInput').value;
            var gender = document.getElementById('stuGenderInput').value;

            if (!studentId) {
                alert('请输入学号');
                return;
            }
            if (!name) {
                alert('请输入姓名');
                return;
            }

            var student = {
                studentId: studentId,
                name: name,
                classId: classId ? parseInt(classId) : null,
                gender: gender
            };

            fetch('/api/student/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(student)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('添加学生成功');
                    closeAddStudent();
                    fetchStudentList();
                } else {
                    alert(result.message || '添加学生失败');
                }
            })
            .catch(error => {
                console.error('添加学生失败:', error);
                alert('添加学生失败，请稍后重试');
            });
        }

        // 编辑学生（打开编辑窗口）
        function editStudent(id) {
            // 获取学生详情
            fetch('/api/student/detail?id=' + id)
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        var student = result.data;
                        // 创建编辑窗口
                        var editModal = document.createElement('div');
                        editModal.className = 'modal-bg';
                        editModal.id = 'editStudentBg';
                        editModal.style.display = 'block';

                        editModal.innerHTML = `
                            <div class="modal">
                                <div class="modal-title">编辑学生</div>
                                <input type="hidden" id="editStudentId" value="${student.id}">
                                <label>学号</label><input id="editStuNoInput" type="text" value="${student.studentId}" placeholder="请输入学号" />
                                <label>姓名</label><input id="editStuNameInput" type="text" value="${student.name}" placeholder="请输入姓名" />
                                <label>班级</label>
                                <select id="editStuClassInput">
                                    ${Array.from(document.getElementById('stuClassInput').options).map(opt =>
                                        `<option value="${opt.value}" ${student.classId == opt.value ? 'selected' : ''}>${opt.text}</option>`
                                    ).join('')}
                                </select>
                                <label>性别</label>
                                <select id="editStuGenderInput">
                                    <option value="男" ${student.gender === '男' ? 'selected' : ''}>男</option>
                                    <option value="女" ${student.gender === '女' ? 'selected' : ''}>女</option>
                                </select>
                                <div class="modal-btns">
                                    <button class="ok" onclick="updateStudent()">确定</button>
                                    <button class="cancel" onclick="closeEditStudent()">取消</button>
                                </div>
                            </div>
                        `;

                        document.body.appendChild(editModal);
                    } else {
                        alert(result.message || '获取学生信息失败');
                    }
                })
                .catch(error => {
                    console.error('获取学生信息失败:', error);
                    alert('获取学生信息失败，请稍后重试');
                });
        }

        // 关闭编辑窗口
        function closeEditStudent() {
            var editModal = document.getElementById('editStudentBg');
            if (editModal) {
                document.body.removeChild(editModal);
            }
        }

        // 更新学生信息
        function updateStudent() {
            var id = document.getElementById('editStudentId').value;
            var studentId = document.getElementById('editStuNoInput').value.trim();
            var name = document.getElementById('editStuNameInput').value.trim();
            var classId = document.getElementById('editStuClassInput').value;
            var gender = document.getElementById('editStuGenderInput').value;

            if (!studentId) {
                alert('请输入学号');
                return;
            }
            if (!name) {
                alert('请输入姓名');
                return;
            }

            var student = {
                id: parseInt(id),
                studentId: studentId,
                name: name,
                classId: classId ? parseInt(classId) : null,
                gender: gender
            };

            fetch('/api/student/edit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(student)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('更新学生信息成功');
                    closeEditStudent();
                    fetchStudentList();
                } else {
                    alert(result.message || '更新学生信息失败');
                }
            })
            .catch(error => {
                console.error('更新学生信息失败:', error);
                alert('更新学生信息失败，请稍后重试');
            });
        }

        // 删除学生
        function deleteStudent(id, studentId) {
            if (!confirm('确定要删除学号为 ' + studentId + ' 的学生吗？')) {
                return;
            }

            fetch('/api/student/delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: id })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('删除学生成功');
                    fetchStudentList();
                } else {
                    alert(result.message || '删除学生失败');
                }
            })
            .catch(error => {
                console.error('删除学生失败:', error);
                alert('删除学生失败，请稍后重试');
            });
        }

        // 添加班级
        function addClass() {
            var className = document.getElementById('classNameInput').value.trim();
            if(!className) {
                alert('请输入班级名称');
                return;
            }

            fetch('/api/class/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name: className })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('新增班级成功');
                    closeAddClass();
                    fetchClassList();
                } else {
                    alert(result.message || '新增班级失败');
                }
            })
            .catch(error => {
                console.error('新增班级失败:', error);
                alert('新增班级失败，请稍后重试');
            });
        }

        // 通用函数
        document.getElementById('userName').onclick = function(e) {
            var menu = document.getElementById('logoutMenu');
            menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
            e.stopPropagation();
        };

        document.body.onclick = function() {
            var menu = document.getElementById('logoutMenu');
            if(menu) menu.style.display = 'none';
        };

        function logout() {
            localStorage.removeItem('loginUser');
            window.location.href = 'login.html'; // 退出后重定向到登录页面
        }

        function closeMenu() {
            setTimeout(function(){
                var menu = document.getElementById('logoutMenu');
                if(menu) menu.style.display = 'none';
            }, 100);
        }

        function showAddStudent() {
            document.getElementById('addStudentBg').style.display = 'block';
        }

        function closeAddStudent() {
            document.getElementById('addStudentBg').style.display = 'none';
            // 清空表单
            document.getElementById('stuNoInput').value = '';
            document.getElementById('stuNameInput').value = '';
        }

        function showAddClass() {
            document.getElementById('addClassBg').style.display = 'block';
        }

        function closeAddClass() {
            document.getElementById('addClassBg').style.display = 'none';
            document.getElementById('classNameInput').value = '';
        }

        // 显示班级管理窗口
        function showManageClass() {
            document.getElementById('manageClassBg').style.display = 'block';
            loadClassList();
        }

        // 关闭班级管理窗口
        function closeManageClass() {
            document.getElementById('manageClassBg').style.display = 'none';
        }

        // 加载班级列表到班级管理窗口
        function loadClassList() {
            fetch('/api/class/list')
                .then(response => response.json())
                .then(data => {
                    var tbody = document.querySelector('#classTable tbody');
                    tbody.innerHTML = '';

                    if (data.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="2" style="text-align:center;">暂无班级数据</td></tr>';
                        return;
                    }

                    data.forEach(cls => {
                        var tr = document.createElement('tr');
                        tr.innerHTML = `
                            <td>${cls.name}</td>
                            <td>
                                <button class="btn btn-danger" onclick="deleteClass(${cls.id}, '${cls.name}')">删除</button>
                            </td>
                        `;
                        tbody.appendChild(tr);
                    });
                })
                .catch(error => {
                    console.error('获取班级列表失败:', error);
                    alert('获取班级列表失败，请稍后重试');
                });
        }

        // 删除班级
        function deleteClass(id, name) {
            // 检查是否有学生使用该班级
            fetch('/api/student/list?classId=' + id)
                .then(response => response.json())
                .then(students => {
                    if (students.length > 0) {
                        alert('该班级下还有学生，无法删除！请先将学生转移到其他班级或删除相关学生。');
                        return;
                    }

                    // 确认删除
                    if (!confirm('确定要删除班级 "' + name + '" 吗？')) {
                        return;
                    }

                    // 执行删除操作
                    fetch('/api/class/delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id: id })
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            alert('删除班级成功');
                            loadClassList(); // 重新加载班级列表
                            fetchClassList(); // 更新页面上的班级下拉框
                        } else {
                            alert(result.message || '删除班级失败');
                        }
                    })
                    .catch(error => {
                        console.error('删除班级失败:', error);
                        alert('删除班级失败，请稍后重试');
                    });
                })
                .catch(error => {
                    console.error('检查班级学生失败:', error);
                    alert('检查班级学生失败，请稍后重试');
                });
        }

        // 导出学生信息
        function exportStudents() {
            var classId = document.getElementById('classSelect').value;
            var className = classId ? document.getElementById('classSelect').options[document.getElementById('classSelect').selectedIndex].text : '全部班级';

            // 构建URL，与获取学生列表相同的参数
            var url = '/api/student/list';
            if (classId) {
                url += '?classId=' + classId;
            }

            // 获取学生数据
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.length === 0) {
                        alert('暂无学生数据可导出');
                        return;
                    }

                    // 按学号排序
                    data.sort((a, b) => a.studentId.localeCompare(b.studentId));

                    // 添加UTF-8 BOM标记，解决中文乱码问题
                    var BOM = new Uint8Array([0xEF, 0xBB, 0xBF]);

                    // 创建CSV内容
                    var csvContent = "学号,姓名,班级,性别\n";

                    data.forEach(student => {
                        // 处理可能包含逗号的字段，用双引号包裹
                        var name = student.name ? `"${student.name.replace(/"/g, '""')}"` : '';
                        var className = student.className ? `"${student.className.replace(/"/g, '""')}"` : '';
                        var gender = student.gender ? `"${student.gender.replace(/"/g, '""')}"` : '';

                        csvContent += `${student.studentId},${name},${className},${gender}\n`;
                    });

                    // 创建Blob对象，添加BOM标记
                    var blob = new Blob([BOM, csvContent], { type: 'text/csv;charset=utf-8;' });

                    // 创建下载链接
                    var link = document.createElement("a");
                    var url = URL.createObjectURL(blob);
                    link.setAttribute("href", url);
                    link.setAttribute("download", `学生名单_${className}_${new Date().toLocaleDateString()}.csv`);
                    link.style.visibility = 'hidden';

                    // 添加到文档并触发点击
                    document.body.appendChild(link);
                    link.click();

                    // 清理
                    document.body.removeChild(link);
                })
                .catch(error => {
                    console.error('导出学生信息失败:', error);
                    alert('导出学生信息失败，请稍后重试');
                });
        }
    </script>
</body>
</html>
